// pages/recovery/recovery.js
import {getRehabilitation,getDoctorInfo,getToppedPlan,getTodayPlanDetail,completePlan,getActionRecord,getMedicalRecord,getPrompt,submitPrompt,getUserInfoUserid} from "../../services/_utils/api"
import Message from "../../miniprogram_npm/tdesign-miniprogram/message/index"
import {GETSTORAGE,SETSTORAGE} from "../../services/storage/storage"
var util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    weekList:[],//周任务列表
    targetList:[],//任务列表
    targetData:[],//任务列表
    day:'',
    dayDate:'',
    problemList:[],//问题列表
    videoList:[],//视频列表
    play_flag: -1,
    emptyFlag:false,//空状态
    taskFlag:false,//任务状态
    talkList:[],//医生嘱咐
    nonePlanFlag:false,
    extendNums:0,//伸目标
    bendNums:0 ,// 屈目标
    extendnum:0,
    bendnum:0,
    remainder:0 //余数
  },
  goTrain(){
    wx.navigateTo({
      url: '/pages/todayTask/todayTask',
    })
  },
  // 是否签协议
  ifSignAgreement(){
    const userid = GETSTORAGE('userId')
    getUserInfoUserid({userId:userid}).then(res => {
      console.log(res,'是否签协议');
      if(res.data.data.kneeSignedAgreementVersion != res.data.data.kneeCurrentAgreementVersion){
        wx.navigateTo({
          url: '/pages/agreement/agreement',
        })
      }
    })
  },
  // 单选框类型输入框
  radioChange(e){
    console.log(e,'单选');
    const {index} = e.currentTarget.dataset
    const {value} = e.detail
    this.data.targetData[index].problem.inputValue = value
    this.setData({
      [`radioVal${index}`]:value,
      targetData:this.data.targetData
    })
  },
  // 多选类型输入框
  checkChange(e){
    console.log(e,'多选');
    const {index} = e.currentTarget.dataset
    const {value} = e.detail
    this.setData({
      [`checkVal${index}`]:value
    })
  },
  // 文本类型输入框
  textChange(e){
    console.log(e,'文本');
    const {index} = e.currentTarget.dataset
    const {value} = e.detail
    this.data.targetData[index].problem.inputValue = value
    this.setData({
      [`textVal${index}`]:value,
      targetData:this.data.targetData
    })
  },
  // 数字类型输入框
  numChange(e){
    console.log(e,'数字');
    const {index,item} = e.currentTarget.dataset
    const {value} = e.detail
    this.data.targetData[index].problem.inputValue = value
    if(Number(item.maxValue)<Number(value)){
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '最大值为'+item.maxValue+'CM',
      });
    }else{
      this.setData({
        [`numVal${index}`]:value,
        targetData:this.data.targetData
      })

    }
    if(item.minValue>value){
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '最小值为'+item.minValue+'CM',
      });
    }else{
      this.setData({
        [`numVal${index}`]:value
      })
    }
   
  },
  // 提交任务
  submitTask(e){
    console.log(e,'=====e=====');
    const {item,index} = e.currentTarget.dataset
     // 传感器
     if(item.type == "SENSOR_GYROSCOPE"){
      this.goTrain()
      return
    }
    const content = item.label+'任务已提交'
    let obj ={
      rehabilitationPlanDetailInputChoiceId:'',
      rehabilitationPlanDetailId:item.problem.rehabilitationPlanDetailId,
      rehabilitationPlanDetailInputContentId:'',
      rehabilitationPlanDetailInputNumId:'',
      inputValue:'',
      choiceInputValue:[]
    }
   
    // 数字
    if(item.type == "INPUT_NUM" && Number(item.problem.maxValue) > Number(this.data[`numVal${index}`])){
      obj.rehabilitationPlanDetailInputNumId = item.problem.id
      obj.inputValue = this.data[`numVal${index}`]
      console.log(obj,'数字obj');
    }
    if(item.type == "INPUT_NUM" && Number(item.problem.maxValue) < Number(this.data[`numVal${index}`])){
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '最大值为'+item.problem.maxValue+'CM',
      });
      return
    }
    // 文本
    if(item.type == "INPUT_CONTENT"){
      obj.rehabilitationPlanDetailInputContentId = item.problem.id
      obj.inputValue = this.data[`textVal${index}`]
      console.log(obj,'文本');
    }
    if(item.type == "INPUT_CHOICE" && item.problem.multiple == 0){
      obj.rehabilitationPlanDetailInputChoiceId = item.problem.id
      obj.choiceInputValue = [this.data[`radioVal${index}`]]
      console.log(obj,'单选');
    }
    if(item.type == "INPUT_CHOICE" && item.problem.multiple == 1){
      obj.rehabilitationPlanDetailInputChoiceId = item.problem.id
      obj.choiceInputValue = this.data[`checkVal${index}`]
      console.log(obj,'多选');
    }
    completePlan(obj).then(res =>{
      Message.success({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: content,
      });
      console.log(res,'任务提交');
      this.getContent()
    })
  },
  // 展开任务
  expandTask(e){
    console.log(e);
    const {i} = e.currentTarget.dataset
    this.data.targetData[i].flag = !this.data.targetData[i].flag
    this.setData({
      targetData:this.data.targetData
    })

  },
  // 查询绑定的医生
  getContent(){
    const userid = GETSTORAGE('userId')
    const memberInfoId = GETSTORAGE('recoveryMemberInfoId')
    console.log(userid,'userid');
    getDoctorInfo({userId:userid,recoveryMemberInfoId:memberInfoId}).then(res => {
      console.log(res,"绑定的医生信息");
      if(res.data.code == 200){
        SETSTORAGE('doctorId',res.data.data.id)
        this.getDoctorPlan()
      }
    })
  },
  // 点击已读
  handleRead(e){
    console.log(e);
    const {id} = e.currentTarget.dataset
    submitPrompt({doctorPatientInteractionId:id}).then(res => {
      console.log(res,'提交成功');
      if(res.data.code == 200){
        this.getContent()
      }
    })
  },
  // 查询医生是否制定计划
  getDoctorPlan(){
    const id = GETSTORAGE('doctorId')
    const medicalRecordId = GETSTORAGE('medicalRecordId')
    console.log(medicalRecordId,'=======medicalRecordId=========');
    getToppedPlan({doctorId:id,medicalRecordId:medicalRecordId}).then(res => {
      console.log(res,'医生是否制定康复计划');
      if(res.data.code == 500){
        this.setData({
          nonePlanFlag:true
        })
        return
      }else{
        this.setData({
          nonePlanFlag:false
        })
      }
      if(res.data.code == 200){
        SETSTORAGE('rehabilitationDate',res.data.data.rehabilitationDate) 
        SETSTORAGE('planId',res.data.data.id)
        getPrompt({developRehabilitationPlanId:res.data.data.id}).then(res => {
          console.log(res);
          if(res.data.code == 500) return
          this.data.talkList = res.data.data
          this.data.talkList.forEach(item => {
            item.talkTime = util.formatTime(new Date(item.talkTime))
          })
          this.setData({
            talkList:this.data.talkList
          })
          console.log(this.data.talkList,'医生嘱咐');

        })
        this.getTodayPlan()
      }
    })
  },
  // 获取当日计划
  getTodayPlan(){
    const id = GETSTORAGE('planId')
    const date = util.formatTime(new Date())
    console.log(date,"============data===========");
    getTodayPlanDetail({developRehabilitationPlanId:id,rehabilitationDate:date,week:''}).then(res =>{
      if(res.data.code == 500 || res.data.data == 'null'){
        this.setData({
          emptyFlag:true
        })
        return
      }
      console.log(res,'当日计划明细');
      let extendnums = ''
      let bendnums = ''
      let extendnum = []
      let bendnum = []
      if(res.data.data.rehabilitationPlanDetailSensorGyroscopesList && res.data.data.rehabilitationPlanDetailSensorGyroscopesList.length>0){
        extendnums = res.data.data.rehabilitationPlanDetailSensorGyroscopesList[0].extensionTimes
        bendnums = res.data.data.rehabilitationPlanDetailSensorGyroscopesList[0].flexionTimes
        SETSTORAGE('extendNums',extendnums)
        SETSTORAGE('bendNums',bendnums)
        extendnum = res.data.data.legRecoveryRecordList.filter(item => item.legAction == '伸')
        bendnum = res.data.data.legRecoveryRecordList.filter(item => item.legAction == '屈')
        SETSTORAGE('extendCompleteNums',extendnum.length)
        SETSTORAGE('bendCompleteNums',bendnum.length)
        this.setData({
          extendNums:extendnums,
          bendNums:bendnums,
          extendnum:extendnum.length,
          bendnum:bendnum.length
        })
      }
     
      this.data.targetData = res.data.data.rehabilitationPlanDetailList
      // 单选
      const choiceProblemList = res.data.data.rehabilitationPlanDetailInputChoiceList
      // 文本
      const contentProblemList = res.data.data.rehabilitationPlanDetailInputContentList
      // 数字
      const numProblemList = res.data.data.rehabilitationPlanDetailInputNumList
      this.data.videoList = res.data.data.rehabilitationPlanDetailVideoList
      choiceProblemList.forEach(item => {
        item.choice = JSON.parse(item.choice)
        item.negativeTerm = JSON.parse(item.negativeTerm)[0]
        if(item.inputValue != ''&& item.inputValue != null){
          item.inputValue = JSON.parse(item.inputValue)[0]
        }
      })
      this.data.targetData.forEach((item,index) => {
          item.flag = false
          // 单选
          for(let i in choiceProblemList){
            if(item.id == choiceProblemList[i].rehabilitationPlanDetailId){
              item.problem = choiceProblemList[i]
            }
          }
          // 文本
          for(let i in contentProblemList){
            if(item.id == contentProblemList[i].rehabilitationPlanDetailId){
              item.problem = contentProblemList[i]
            }
          }
          // 数字
          for(let i in numProblemList){
            if(item.id == numProblemList[i].rehabilitationPlanDetailId){
              item.problem = numProblemList[i]
            }
          }
          for(let i in this.data.videoList){
            if(item.id == this.data.videoList[i].rehabilitationPlanDetailId){
              item.video = this.data.videoList[i]
              item.video.flag = -1
            }
          }
          if(item.type == "SENSOR_GYROSCOPE"){
            if(extendnum.length >= extendnums && bendnum.length >= bendnums){
              const obj = {
                inputValue:'完成'
              }
              item.problem = obj
              console.log(item,'item========');
            }
          }
      })
      this.data.targetData.forEach((item,index) => {
        if(item.label == '腿部屈伸练习'){
          this.data.targetData.splice(index,1)
          this.data.targetData.unshift(item)
        }
      })
      
      this.setData({
        targetData:this.data.targetData,
        problemList:this.data.problemList
      })
      console.log(this.data.targetData,'=========targetData==========');
      // this.data.targetData.forEach((item,index) => {
      //   if(item?.problem && item.problem?.inputValue == item.problem?.negativeTerm || item.problem?.inputValue == ''|| item.problem?.inputValue == null){

      //   }else{
      //     this.data.targetData.splice(index,1)
      //     this.data.targetData.push(item)
      //     this.setData({
      //       targetData:this.data.targetData
      //     })
      //   }
      // })
      const arr = this.data.targetData.filter(item => item?.problem && item.problem?.inputValue == item.problem?.negativeTerm || item.problem?.inputValue == ''|| item.problem?.inputValue == null)
      const arr1 = this.data.targetData.filter(item => item?.problem && item.problem?.inputValue != item.problem?.negativeTerm && item.problem?.inputValue != ''&& item.problem?.inputValue != null)
      const arr2 = [...arr,...arr1]
      this.setData({
        targetData:arr2
      })
      const list = this.data.targetData.filter(item => item.problem?.inputValue == null)
      if(list.length == 0){
        this.setData({
          taskFlag:true
        })
      }
      this.getWeekData(this.data.day)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getWeekData(value){
    
    const id = GETSTORAGE('planId')
    const date = util.formatTime(new Date())
    console.log(date,"============data===========");
    getTodayPlanDetail({developRehabilitationPlanId:id,rehabilitationDate:'',week:value}).then(res =>{
      console.log(res,'周计划');
      // if(res.data.code == 500 || res.data.data == 'null'){
      //   this.setData({
      //     emptyFlag:true
      //   })
      //   return
      // }
      if(res.data.code == 500) return
      this.data.targetList = res.data.data.rehabilitationPlanDetailList
      // 单选
      const choiceProblemList = res.data.data.rehabilitationPlanDetailInputChoiceList
      // 文本
      const contentProblemList = res.data.data.rehabilitationPlanDetailInputContentList
      // 数字
      const numProblemList = res.data.data.rehabilitationPlanDetailInputNumList
      // 训练腿部
      const legList = res.data.data.rehabilitationPlanDetailSensorGyroscopesList
      this.data.videoList = res.data.data.rehabilitationPlanDetailVideoList
      choiceProblemList.forEach(item => {
        item.choice = JSON.parse(item.choice)
        if(item.inputValue == item.negativeTerm){
          item.inputValue = null
        }
      })
      this.data.targetList.forEach(item => {
          item.flag = false
          // 单选
          for(let i in choiceProblemList){
            if(item.id == choiceProblemList[i].rehabilitationPlanDetailId){
              item.problem = choiceProblemList[i]
            }
          }
          // 文本
          for(let i in contentProblemList){
            if(item.id == contentProblemList[i].rehabilitationPlanDetailId){
              item.problem = contentProblemList[i]
            }
          }
          // 数字
          for(let i in numProblemList){
            if(item.id == numProblemList[i].rehabilitationPlanDetailId){
              item.problem = numProblemList[i]
            }
          }
          for(let i in this.data.videoList){
            if(item.id == this.data.videoList[i].rehabilitationPlanDetailId){
              item.video = this.data.videoList[i]
              item.video.flag = -1
            }
          }
          for(let i in legList){
            if(item.id == legList[i].rehabilitationPlanDetailId){
              item.problem = legList[i]
            }
          }
          if(item.type == "SENSOR_GYROSCOPE"){
           let extendnum = res.data.data.legRecoveryRecordList.filter(ele => ele.legAction == '伸' && item.rehabilitationDate == ele.testTime)
           let bendnum = res.data.data.legRecoveryRecordList.filter(ele => ele.legAction == '屈' && item.rehabilitationDate == ele.testTime)
            if(extendnum.length >= item.problem.extensionTimes && bendnum.length >= item.problem.flexionTimes){
             item.problem.inputValue = '完成'
            }else{
              item.problem = ''
            }
          }
      })
      console.log(this.data.targetList);
      this.setData({
        targetList:this.data.targetList,
      })
      // const list = this.data.targetList.filter(item => item.problem?.inputValue == null)
      // if(list.length == 0){
      //   this.setData({
      //     taskFlag:true,
      //   })
      // }
      let titleList = this.data.targetList.map((item) => {
        return item.label
      })
      let titleObj =  util.getRepeatNum(titleList)
      this.setData({
        weekList:[]
      })
      Object.keys(titleObj).forEach(key => {
        const value = titleObj[key];
        this.data.weekList.push({
          label: key,
          sum: value
        })
      });
      this.data.weekList.forEach((items, index) => {
        this.data.targetList.forEach((element) => {
          if (items.label == element.label) {
            if (element.problem?.inputValue == null || element.problem?.inputValue == '') {
              this.data.weekList[index].accomplish = (this.data.weekList[index].accomplish || 0) + 1;
            }else{
              this.data.weekList[index].accomplish  = (this.data.weekList[index].accomplish || 0) 
            }
          }
        })
      })
      console.log(this.data.weekList,'this.data.weekList');
       this.data.weekList.forEach(item=>{
        item.accomplish = item.sum - item.accomplish,
        console.log(item.accomplish,item.sum,'===========sssssssss========');
        item.probability = ((item.accomplish/item.sum)*100).toFixed(0)
        console.log( (((item.accomplish/item.sum)).toFixed(2)),'========33333333===========');
      })
      this.setData({
        weekList:this.data.weekList,
      })
      console.log(this.data.weekList)
    })
  },
  onLoad(options) {
    // this.getContent()
    // if(this.data.day){
    //   this.getWeekData()
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    SETSTORAGE('actionOk',false)
    // var that = this;
    // that.data.videoContext = wx.createVideoContext('myVideo');
  },
  // 视屏播放
  bind_play(e) {
    const {index} = e.currentTarget.dataset
    const videoContext = wx.createVideoContext(`myVideo${index}`)
    this.data.targetData.forEach((item,i) => {
      if(index == i && item.video){
        console.log(i,index,'=======i=========');
        item.video.flag = 0
      }else{
        if(!item.video) return
        item.video.flag = -1
        wx.createVideoContext(`myVideo${i}`).pause()
      }
    })
    this.setData({
      targetData:this.data.targetData
    });
    videoContext.requestFullScreen({ direction: 90 });
    videoContext.play();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    this.getWeekData()
    const rehabilitationDatere = GETSTORAGE('rehabilitationDate')
    let old = util.formatTime(new Date())
    let weekDay = util.getDiffDay(old,rehabilitationDatere)
   this.setData({
    day:weekDay/7<1?1:parseInt(weekDay/7),
    dayDate:weekDay+1,
    remainder:(weekDay+1)%7
   })
   console.log(this.data.remainder,'remainder');
   console.log(weekDay,'weekDay%7');
    if(this.data.day != ''){
      this.getWeekData(this.data.day)
    }
    // this.ifSignAgreement()
    this.getContent()
    const legFlag = GETSTORAGE('actionOk')
    if(legFlag){
      Message.success({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: '腿部训练任务已提交',
      });
      SETSTORAGE('actionOk',false)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})